package com.ljm.commom.web.filter;

import com.ljm.commom.web.http.BodyReaderRequestWrapper;
import com.ljm.commom.web.utils.RequestIpUtils;
import com.ljm.common.constants.SysConstants;
import com.ljm.common.util.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.UUID;

/**
 * @author ChenHuaMing
 * 版权：    Copyright by ljm
 * 描述：
 * 修改人：  HuamingChen
 * 修改时间：2020/3/6
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */
public class BodyReaderRequestFilter implements Filter {
    private final static Logger logger= LoggerFactory.getLogger(BodyReaderRequestFilter.class);
    @Override
    public void init(FilterConfig filterConfig){

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        BodyReaderRequestWrapper bodyReaderRequestWrapper = new BodyReaderRequestWrapper(httpServletRequest);
        // 增加traceId,方便日志跟踪
        String trackId= UUID.randomUUID().toString();
        MDC.put(SysConstants.LOG_TRACE_ID, trackId);
        SysConstants.TRACKID_TL.set(trackId);
        String requestIp = RequestIpUtils.getIpAddr(httpServletRequest);
        SysConstants.IP_TL.set(requestIp);
        MDC.put(SysConstants.SERVICE_IP, IpUtils.getLocalIpAddress());
        MDC.put(SysConstants.REQUEST_IP, requestIp);
        try {
            filterChain.doFilter(bodyReaderRequestWrapper,servletResponse);
        } catch (IOException e) {
            throw e;
        } catch (ServletException e) {
            throw e;
        } finally {
            SysConstants.clearIpThreadLocal();
            SysConstants.clearTrackIdThreadLocal();
            SysConstants.clearLoginNameThreadLocal();
        }
    }

    @Override
    public void destroy() {
        SysConstants.clearIpThreadLocal();
        SysConstants.clearTrackIdThreadLocal();
        SysConstants.clearLoginNameThreadLocal();
    }
}
